//
//  XPhotoBrowser.m
//  XPhotoLibraryKit
//
//  Created by Wu,Xinting on 2018/3/21.
//

#import "XPhotoBrowser.h"
#import "XPhoto.h"
#import "XPhotoBrowserCell.h"

static NSString *ReuseBrowserCellIdentify = @"ReuseBrowserCellIdentify";
@interface XPhotoBrowser () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate>

@property (nonatomic, strong) UITapGestureRecognizer *tapGR;
@property (nonatomic, strong) UITapGestureRecognizer *doubleTapGR;
@property (nonatomic, strong) UIPanGestureRecognizer *panGR;
@property (nonatomic, strong) UIPinchGestureRecognizer *pinchGR;

@end

@implementation XPhotoBrowser

- (instancetype)initWithFrame:(CGRect)frame {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    return [self initWithFrame:frame collectionViewLayout:layout];
}

- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout {
    if (self = [super initWithFrame:frame collectionViewLayout:layout]) {
        self.delegate = self;
        self.dataSource = self;
        self.pagingEnabled = YES;
        [self registerClass:[XPhotoBrowserCell class] forCellWithReuseIdentifier:ReuseBrowserCellIdentify];
        
        self.tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGR:)];
        self.userInteractionEnabled = YES;
        [self addGestureRecognizer:self.tapGR];
        
        self.doubleTapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapGR:)];
        self.doubleTapGR.numberOfTapsRequired = 2;
        [self.tapGR requireGestureRecognizerToFail:self.doubleTapGR];
        [self addGestureRecognizer:self.doubleTapGR];
        
        self.panGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGR:)];
        self.pinchGR = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGR:)];
        [self addGestureRecognizer:self.panGR];
        [self addGestureRecognizer:self.pinchGR];
        self.panGR.delegate = self;
        
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)dealloc {
    [self removeGestureRecognizer:self.tapGR];
    [self removeGestureRecognizer:self.doubleTapGR];
}

- (void)animationSourceView:(UIView *)sourceView {
    // 不能映射到自身，自身是Scroll属性的，会有偏差
    CGRect rectInBrowser = [sourceView.superview convertRect:sourceView.frame toView:nil];
    _sourceRect = rectInBrowser;
}

- (void)animationTargetView:(UIView *)targetView {
    CGRect rectOutBrowser = [targetView.superview convertRect:targetView.frame toView:nil];
    _targetRect = rectOutBrowser;
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if ([gestureRecognizer isEqual:self.panGR]) {
        CGPoint point = [self.panGR locationInView:self];
        NSIndexPath *touchIndexPath = [self indexPathForItemAtPoint:point];
        UICollectionViewCell *cell = [self cellForItemAtIndexPath:touchIndexPath];
        if (![cell isKindOfClass:[XPhotoBrowserCell class]]) return NO;
        XPhotoBrowserCell *pbCell = (XPhotoBrowserCell *)cell;
        return [pbCell shouldTranslate:[self.panGR translationInView:self]];
    }
    return YES;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.browserDataSource numberOfPhotosInPhotoBrowser:self];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XPhotoBrowserCell *photoCell = [collectionView dequeueReusableCellWithReuseIdentifier:ReuseBrowserCellIdentify forIndexPath:indexPath];
    photoCell.sourceRect = self.sourceRect;
    photoCell.photo = [self.browserDataSource photoBrowser:self photoForIndex:indexPath.row];
    [photoCell refresh];
    return photoCell;
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return collectionView.bounds.size;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    _currentIndex = indexPath.row;
    if (self.browserDelegate && [self.browserDelegate respondsToSelector:@selector(photoBrowser:displayItemAtIndex:)]) {
        [self.browserDelegate photoBrowser:self displayItemAtIndex:indexPath.row];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if (![cell isKindOfClass:[XPhotoBrowserCell class]]) return;
    XPhotoBrowserCell *pbCell = (XPhotoBrowserCell *)cell;
    [pbCell endDisplay];
}

#pragma mark - Action
- (void)panGR:(UIPanGestureRecognizer *)gr {
    CGPoint tran = [gr translationInView:self];

    UICollectionViewCell *cell = [self cellForItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0]];
    if (![cell isKindOfClass:[XPhotoBrowserCell class]]) return;
    XPhotoBrowserCell *pbCell = (XPhotoBrowserCell *)cell;

    pbCell.photo.transform = CGAffineTransformTranslate(pbCell.photo.transform, tran.x, tran.y);
    [pbCell updatePhoto:NO];

    [gr setTranslation:CGPointZero inView:self];

    if (gr.state == UIGestureRecognizerStateEnded) {
        [pbCell checkPosition];
    }
}

- (void)pinchGR:(UIPinchGestureRecognizer *)gr {
    UICollectionViewCell *cell = [self cellForItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0]];
    if (![cell isKindOfClass:[XPhotoBrowserCell class]]) return;
    XPhotoBrowserCell *pbCell = (XPhotoBrowserCell *)cell;

    pbCell.photo.transform = CGAffineTransformScale(pbCell.photo.transform, gr.scale, gr.scale);
    [pbCell updatePhoto:NO];

    [gr setScale:1.f];

    if (pbCell.photo.transform.a < 1) {
        pbCell.photo.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.f, 1.f);
        [pbCell updatePhoto:YES];
    }
}

- (void)tapGR:(UITapGestureRecognizer *)gr {
    UICollectionViewCell *cell = [self cellForItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0]];
    if (![cell isKindOfClass:[XPhotoBrowserCell class]]) return;
    XPhotoBrowserCell *pbCell = (XPhotoBrowserCell *)cell;
    pbCell.targetRect = self.targetRect;
    [pbCell closeAnimate:^{
        self.hidden = YES;
    }];
}

- (void)doubleTapGR:(UITapGestureRecognizer *)gr {
    UICollectionViewCell * cell = [self cellForItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0]];
    if (![cell isKindOfClass:[XPhotoBrowserCell class]]) return;
    
    XPhotoBrowserCell *pbCell = (XPhotoBrowserCell *)cell;
    if (pbCell.photo.transform.a > 1) {
        pbCell.photo.transform = CGAffineTransformIdentity;
    } else {
        pbCell.photo.transform = CGAffineTransformScale(CGAffineTransformIdentity, 2, 2);
    }
    [pbCell updatePhoto:YES];
}

#pragma mark - Get&Set
- (void)setCurrentIndex:(NSUInteger)currentIndex {
    if (_currentIndex != currentIndex) {
        [self scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:currentIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
        _currentIndex = currentIndex;
    }
}

@end
